package org.oy.sealogger.ds;

import org.apache.log4j.Logger;
import org.oy.sealogger.common.Config;
import org.oy.sealogger.device.Device;
import org.oy.sealogger.device.SerialDevice;
import org.oy.sealogger.device.gps.GPSLinuxFileDevice;
import org.oy.sealogger.device.gps.GPSMacOSXFileDevice;
import org.oy.sealogger.device.gps.GPSSerialDevice;
import org.oy.sealogger.device.gps.GPSSimulatorDevice;
import org.oy.sealogger.ds.nmea.NMEA0183DataSource;
import org.oy.sealogger.ds.nmea.NMEA0183InputAnalyser;

/**
 * Provides static factory methods for different types of data sources.
 * @author riku
 *
 */
public class DataSourceFactory {
	
	private static Logger log = Config.getLogger();
	
	public static <T> DataSource createGPSDataSource(Class<T> dsType, boolean terminateOnError) {
		
		if(dsType == NMEA0183DataSource.class) {
			
			NMEA0183DataSource ds = null;
			InputAnalyser ia = new NMEA0183InputAnalyser();
			Device d;

			try {
				Class deviceClass = Class.forName(Config.getProperty("gps.device"));
				
				// No direct class instantiation attempts for security reasons
				if(deviceClass == SerialDevice.class ||
						deviceClass == GPSSerialDevice.class ||
						deviceClass == GPSSimulatorDevice.class ||
						deviceClass == GPSLinuxFileDevice.class ||
						deviceClass == GPSMacOSXFileDevice.class) {
					
					d = (Device)deviceClass.newInstance();
					d.setInputAnalyser(ia);
					ds = new NMEA0183DataSource(d, terminateOnError);
				}				
			} catch (ClassNotFoundException e) {
				log.error(e);
			} catch(InstantiationException e) {
				log.error(e);
			} catch(IllegalAccessException e) {
				log.error(e);
			}
			
			return ds;
		}
		
		return null;
	}
}
